<?php

/**
 * 默认控制器
 */
class Controller_Interface extends Controller_Abstract
{
// session: 610012757f6964b67189fa014a8a04443ac166b81698da872011132
// refresh_token: 6100e27d7c29a8b161c4d42aa5881ed19721e297cd9e22172011132
//			$c->appkey = '21482531';
//			$c->secretKey = '4c11a1ddf2ebb9d35565abcfb6501ed2';
	private $leftchar = '{';
	private $rightchar = '}';
	private $token = "610160867018e48112167cd85a9994dd9bad5b61872db0c72011132";
    function _loadtoken()
    {
    	
			$token = Acct::find('id = 1')->setColumns('id,tbtoken')->getOne();
		
		if (!$token->id())
		{
			return '';
		}else{
			return trim($token->tbtoken);
		}
    }
    function actionCode()
    {
        return Helper_Ckcode::entry();
    }
    /**
     * 卡密检测是否被使用
     */
    function actioncardcheck()
    {
    	$cardid = trim($this->_context->cardid);
    	$card = Vouchercard::find('cardname = ? and enable = 1 and vouchered = 0 ',$cardid)->setColumns('id')->getOne();
    		
    	if (!($card->id))
    	{
    		#不能使用
    		$this->_response('00');
    	}else
    	{	#可以使用
    		$this->_response('11');
    	}
    }
    function actiongetrate()
    {
    	$agent_id = intval($this->_context->agent_id);
    	$data = Rategroup::find('agent_id = ?',$agent_id)->setColumns('id,rategroupname')->asArray()->getAll();
    	$result = '';
    	foreach ($data as $k=>$v)
    	{
    		$result.= '<option value="'.$v['id'].'">'.$v['rategroupname'].'</option>';
    	}
    	exit($result);
    }
    /**
     * 删除注销用户
     * Enter description here ...
     */
    function actiondropuser()
    {
    	$mobile = $this->_context->get('mobile');
    	$mobile = Helper_Common::trim($mobile);
    	 
    	$pwd = $this->_context->get('pwd');
    	if($mobile && $pwd)
    	{
    		$acctuser = Acctuser::find('acctname = ? and password = ?',$mobile,$pwd)->getOne();
    		if ($acctuser->id())
    		{
    			try {
    			Acctuser::meta()->deleteWhere('id = ?',$acctuser->id);
    			$result = '0';
    			} catch (Exception $e) {
    			$result = '2'; //数据出错
    			}
    		}
    	}else {
    		$result = '1';//格式不正确
    	}
    	$this->_response(2);
    }
    /**
     * 用户余额查询接口
     * Enter description here ...
     */
    function actionbalance()
    {
    	$mobile = $this->_context->get('mobile');
    	$mobile = Helper_Common::trim($mobile);
    	$pwd = $this->_context->get('pwd');
    	if (!Helper_Param::_phone($mobile))
    	{
    		$result = sprintf('%f',0);
    	}else
    	{
    		$user = Acctuser::checkAcctname($mobile);
    		//$bind = Userbindtel::find('bindtel = ?',$mobile)->setColumns('id,acctname')->getOne();
    		if(!$user->id() || $user->password !== $pwd)
    		{
    			$result = sprintf('%f',0);
    		}else{
    			$result = sprintf('%f',isset($user->balance)?$user->balance:0);
    			$result .= ' 有效期至:'.$user->expireddate;
    		}
    	}
    	$this->_response($result);
    }
    function actionchangePwd()
    {
    	$mobile = $this->_context->get('mobile');
    	$mobile = Helper_Common::trim($mobile);
    	$oldPassWord = $this->_context->get('pwd');
    	$newpwd = trim($this->_context->get('newpwd'));
    	
    	if(!Helper_Param::_phone($mobile))
    	{
    		$result = '1'; //手机号码格式不正确
    	}else{
    		$user = Acctuser::checkAcctname($mobile);
    		if(!$user->id())
    		{
    			$result = '2'; //不存在此绑定号码
    		}else{
    			if($user->password !== $oldPassWord)
    			{
    				$result = '3'; //原始密码错误
    			}else{
    				$user->password = $newpwd;
    				try {
	    				$user->save(0,'update');
	    				$sip = Sipbindten::find('accountcode = ?',$mobile)->getOne();
	    				if($sip->id())
	    				{
	    					$sip->secret = $newpwd;
	    					$sip->save(0,'update');
	    				}
	    				//QDB::getConn()->execute("update sip_bindexten_buddies set secret ='{$newpwd}' where accountcode = '{$mobile}'");
	    				$result = '0'; //正确 修改
    				} catch (Exception $e) {
    					$result = '4' ;//数据库保存失败
    				}
    			}
    		}
    	}
    	$this->_response($result);
    }
    function actiongroupcall()
    {
    	$mobile = $this->_context->get('mobile');
    	$mobile = Helper_Common::trim($mobile);
    	$pwd = $this->_context->get('pwd');
    	$phone = $this->_context->get('phone');
    	$password = $this->_context->get('password');
    	$result = '0';
    	if(!Helper_Param::_phone($mobile))
    	{
    		$result = '1'; //手机号码格式不正确
    	}else{
	    	if (!$phone)
	    	{
	    		$result = '1';
	    	}
	    	$phone = explode(',',$phone);
	    	if (count($phone)>0)
	    	{
	    		foreach($phone as $k=>$v)
	    		{
	    			if (!Helper_Param::_phone($v))
	    			{
	    				$result = '5';
	    				break;
	    			}
	    		}
	    		if($result == '0')
	    		{
	    			$user = Acctuser::checkAcctname($mobile);
	    			if (!$user->id()){
	    				$result = '2'; //不存在此绑定号码
	    			}else if($user->password !== $pwd){
	    				$result = '3' ;//密码不正确
	    			}else{
	    				$isone = conference::find('caller = ? and called = ?',$mobile,implode('-',$phone))->getCount('id');
// 	    				if($isone){
// 	    					$result = '4';//存在此呼叫队列 请勿重复提交
// 	    				}else{
	    					
	    						Cbsubmit::groupcall($mobile, implode('-',$phone),$password);
	    						$result = '0';//提交成功
	    					
	    				//}
	    			}		
	    		}
	    
	    	}
    	}
    	$this->_response($result);
    }
    function actioncall()
    {
    	$mobile = $this->_context->get('mobile');
    	$mobile = Helper_Common::trim($mobile);
    	$pwd = $this->_context->get('pwd');
    	$phone = $this->_context->get('phone');
    	if(!Helper_Param::_phone($mobile))
    	{
    		$result = '1'; //手机号码格式不正确
    	}else{	
    		$user = Acctuser::checkAcctname($mobile);
    		if (!$user->id()){
    			$result = '2'; //不存在此绑定号码
    		}else if($user->password !== $pwd){
    			$result = '3' ;//密码不正确
    		}else{
    			$isone = Cbsubmit::find('bindname = ? and destination_number = ?',$mobile,$phone)->getCount('id');
    			if($isone){
    				$result = '4';//存在此呼叫队列 请勿重复提交
    			}else{
    				if(!Helper_Param::_phone($phone))
    				{
    					$result = '5';//被叫号码格式不正确
    				}else{
    					Cbsubmit::call($mobile, $phone);
    					$result = '0';//提交成功
    				}
    				
    			}
    		}
    	}	
    	$this->_response($result);
    }
    function actionpay()
    {
    	$mobile = $this->_context->get('mobile');
    	$mobile = Helper_Common::trim($mobile);
    	$cardid = $this->_context->get('cardid');
    	$cardpwd = $this->_context->get('cardpwd');
    	if(!Helper_Param::_call($mobile))
    	{
    		$result = 'ERR1'; //手机号码格式不正确
    	}else{	
    		//$user = Acctuser::checkAcctname($mobile);
    		//if(!$user->id())
    		//{
    		//	$result = 'ERR2'; //不存在此绑定号码
    		//}else{
    			$flag = Acctuser::use_card($mobile, $cardid, $cardpwd);
				if($flag === true)
				{
					$card = Vouchercard::find('cardname = ? and password = ?',$cardid,$cardpwd)->setColumns('id,balance')->getOne();
					$result = $card->balance;
				}else{
					$result = 'ERR3';
				}
    		//}
    	}
    	$this->_response($result);
    }
    
	function actionUpload()
	{
		$allowExt = 'jpg,png,gif,bmp,swf';
		$upFolder = 'uploadfiles/tmp/';
		if($this->_context->isPOST())
		{
			$errorString  = '';
			# 图片上传
			$uploader = new Helper_Uploader();
			if ($uploader->filesCount()){
				$uploader = new Helper_Uploader();
				$upfile = $uploader->file('uploadfile');
				$extname = $upfile->extname();# 扩展名
				$old_name = $upfile->filename();
				if($upfile->isSuccessed()){
					if($upfile->isValid($allowExt)){
						$filename = md5($old_name.time()).'.'.$extname;
						$filepath = $upFolder.$filename;
						# 移动文件
						$upfile->move($filepath);
						if (!$upfile->isMoved()){
							$errorString = '图片上传失败!请检查服务器配置!';
						}else{
							$errorString = '图片上传成功!';
							$this->_view['filepath'] = $filepath;
						}
					}else{
						$errorString = '图片上传失败!图片格式不正确!';
					}
				}else{
					$errorString = '图片上传失败!请检查服务器配置!';
				}
			}
			unset($uploader);
			$this->_view['errorString'] = $errorString;
			$this->_viewname = 'uploadpost';
		}else{
			$this->_viewname = 'upload';
		}
	}
    function _response($data)
    {
    	exit($this->leftchar.$data.$this->rightchar);
    }
    function actionSendmail()
    {
    	
    	//$acct =QDB::getConn('devel')->getAll("select balance,email from acct where admin_id = agent_id and (admin_id <> -1) and email<>''");
    	#一级代理
    	$acct = Acct::find("admin_id = agent_id and (admin_id <> -1) and email<>''")->getall();
    	foreach ($acct as $item)
    	{
    		$postdata = array(
    				'years'=>date('Y',time()),
    				'month'=>date('m',time()),
    				'agent_id'=>$item->id,
    				'begin_day'=>date('d',strtotime('- day')),
    				'end_day'=>date('d',time()),
    				'billsec_count'=>6,
    				'agent_acctname'=>$item->acctname
    		);
    	
    		$_SESSION['acct'] = $item->toArray();
    		$rows = Cost::callhistory_list_cost($postdata);
    	
    		$message = "您当前的余额为:{$item->balance}<br>";
    	
    		if (($rows))
    		{
    			$message .= "{$postdata['years']}/{$postdata['month']}/{$postdata['begin_day']}-{$postdata['end_day']} 统计数据如下:<br>";
    			$message .= "总计：{$rows[0]['billsec']}秒<br>";
    			$message .= "6秒个数:{$rows[0]['billsec6']}<br>";
    			//$message .= "成本：{$rows[0]['cost']}<br>";
    			$message .= "消费：{$rows[0]['fees']}<br>";
    			$message .= "短信条数:".$item->getAcctSmsCount(strtotime($postdata['begin_day']),strtotime($postdata['end_day']));
    			//$lirun = $rows[0]['fees'] - $rows[0]['cost'];
    			//$message .= "利润：{$lirun}<br>";
    		}
    		$flag = Helper_mail::sendMail($item->email, "您的收据编号".date('YmdHis'), $message);
    		$flagstr = $flag ? '成功':'失败';
    		echo '一级：'.$postdata['agent_acctname'].$flagstr.'<br>';
    	}
    	$acctarray = $acct->toArray(0);
    	$tmp = Helper_Array::toHashmap($acctarray, 'id','id');
    	
    	#二级代理
    	if (count($tmp))
    	{
    		$accttwo = Acct::find('agent_id = ?',implode(',', $tmp))->getAll();
    		
    		foreach ($accttwo as $item)
    		{
    			$postdata = array(
    					'years'=>date('Y',time()),
    					'month'=>date('m',time()),
    					'agent_id'=>$item->id,
    					'begin_day'=>date('d',strtotime('- day')),
    					'end_day'=>date('d',time()),
    					'billsec_count'=>6,
    					'agent_acctname'=>$item->acctname
    			);
    			 

    			
    			if($item->parent->email && $item->parent->emailpass && $item->parent->emailadd)
    			{
    				$userarr = explode( '@',$item->parent->email);
    				
    				if(count($userarr) == 2)
    				{
    					$user = $userarr[0];
    					$pass = $item->parent->emailpass;
    					$emailadd = $item->parent->emailadd;
    					
    				}else{
    					continue;
    				}
    			}else{
    				continue;
    			}
    			
    			$_SESSION['acct'] = $item->toArray();
    			$rows = Cost::callhistory_list_cost($postdata);
    			 
    			$message = "您当前的余额为:{$item->balance}<br>";
    			 
    			if (($rows))
    			{
    				$message .= "{$postdata['years']}/{$postdata['month']}/{$postdata['begin_day']}-{$postdata['end_day']} 统计数据如下:<br>";
    				$message .= "总计：{$rows[0]['billsec']}秒<br>";
    				$message .= "6秒个数:{$rows[0]['billsec6']}<br>";
    				//$message .= "成本：{$rows[0]['cost']}<br>";
    				$message .= "消费：{$rows[0]['fees']}<br>";
    				$message .= "短信条数:".$item->getAcctSmsCount(strtotime($postdata['begin_day']),strtotime($postdata['end_day']));
    				//$lirun = $rows[0]['fees'] - $rows[0]['cost'];
    				//$message .= "利润：{$lirun}<br>";
    			}
    			$flag = Helper_mail::sendMailOnuser($user,$pass,$emailadd,$item->parent->email,$item->email, "您的收据编号".date('YmdHis'), $message);
    			$flagstr = $flag ? '成功':'失败';
    			echo '二级：'.$postdata['agent_acctname'].$flagstr.'<br>';
    		}
    	}
    	exit();
    }
    /**
     * 免费注册
     */
    function actionwebid()
    {
    	$payid = trim($this->_context->payid);
    	$mobile = trim($this->_context->mobile);
    	$mobile = Helper_Common::trim($mobile);
    	$unionuser = trim($this->_context->unionuser);
    	if (strlen($payid)<2 || strlen($mobile)<2 )
    	{
    		$result = '数据不完整';//数据不完整
    	}
    	$isNew = Acctuser::find('acctname = ?',$mobile)->getCount('id');
    	if ($isNew>0)
    	{
    		$result = '只能新建立用户';//只能新建
    	}
    	$card = Vouchercard::find('payid = ? and enable = 1 and vouchered = 0',$payid)->getOne();
    	if (!$card->id())
    	{
    		$result = '没用免费注册卡可用'; //无卡
    	}
    	$cardid = $card->cardname;
    	$cardpwd = $card->password;
    	if(!Helper_Param::_call($mobile))
    	{
    		$result = '手机号码不正确';
    	}else{
    		$flag = Acctuser::use_card($mobile, $cardid, $cardpwd,'',$unionuser);
    		if($flag === true)
    		{
    			//$card = Vouchercard::find('cardname = ? and password = ?',$cardid,$cardpwd)->setColumns('id,balance')->getOne();
    			$result = '0';
    		}else{
    			$result = '开户失败';
    		}
    	
    	}
    	$this->_response($result);
    }
    
    function actionagentpay()
    {
    	//acctname=平台号&password=密码&caller=被冲值账号&balance=金额&rategroupid_acall=回另费率&rategroupid=呼出费率
		$acctname = isset($this->_context->acctname) ? trim($this->_context->acctname) : null;
		$acctname = Helper_Common::trim($acctname);
		$password = isset($this->_context->password) ? trim($this->_context->password) : null;
		$caller = isset($this->_context->caller) ? trim($this->_context->caller) : null;
		$balance = isset($this->_context->balance) ? trim($this->_context->balance) : null;
		$rategroupid_acall = isset($this->_context->rategroupid_acall) ? intval($this->_context->rategroupid_acall) : null;
		$rategroupid = isset($this->_context->rategroupid) ? intval($this->_context->rategroupid) : null;
		$expday = isset($this->_context->expday) ? intval($this->_context->expday) : 360;
		if(is_null($acctname) || is_null($password) || is_null($caller) || is_null($balance) || is_null($rategroupid_acall) || is_null($rategroupid) || is_null($expday))
		{
			$result = 'ERR1';
		}else{
			$agent = Acct::find('acctname = ? and password = ?',$acctname,$password)->getOne();
			if(!$agent->id())
			{
				$result = 'ERR2';
			}else{
				$rate1 = Rategroup::find('id = ? and agent_id = ?',$rategroupid_acall,$rategroupid,$agent->id)->getCount('id');
				$rate2 = Rategroup::find('id = ? and agent_id = ?',$rategroupid,$rategroupid,$agent->id)->getCount('id');
				
				if($rate1 ==1 && $rate2 ==1)
				{
					$result = 'ERR3';
				}else{
					$card = array(
							'agent_id'=>$agent->id,
							'admin_id'=>$agent->admin_id,
							'balance' =>$balance,
							'limitbalance'=>0,
							'expireddays'=>$expday,
							'rategroupid'=>$rategroupid,
							'rategroupid_acall'=>$rategroupid_acall,
							'bindexten'=>'',
							'voucher_acctname'=>'',
							'expireddate'=>date('Y-m-d',strtotime("+ 360 day")),
							'voucheredtype'=>2
							);
					$item = Helper_Common::get_rnd(0,9);
					$card['password'] = Helper_Common::get_rnd(0,6);
					$card['cardname'] = $item;
					$status = Acct::make_card($agent->id, $card);
					if($status)
					{
						$new = Acctuser::use_card($caller, $card['cardname'], $card['password']);
						if($new)
						{
						    $user = Acctuser::checkAcctname($caller);
						    if($user->id())
						    {
						        $result = sprintf("%s,%s,%s,%s",$balance,$user->expireddate,$user->balance,$user->password);
							
						    }else{
						        $result = 'ERR4';
						    }
						}else{
							$result = 'ERR4';
						}
					}else{
						$result = 'ERR5';
					}
				}
					
			}
			
		}
		$this->_response($result);
    }
	function actionweb800()
	{
		$aid = intval($this->_context->aid);
		$isAcct = Acctuser::find('id = ?',$aid)->getOne();
		if (!$isAcct->id()){exit('err');}
		$err = '';
		
		$now = (str_replace(':', '', date('H:i')));
		
		if($this->_context->isPOST())
		{
			if (!Helper_Ckcode::check($this->_context->codeOK))
			{
				$err = "验证码错误";
			}else{
				$mobile = trim($this->_context->mobile);
				$mobile = Helper_Common::trim($mobile);
				if (!Helper_Param::_phone($mobile))
				{
					$err = "手机号码不正确";
				}else{
					$isRuning = Calllist::find('caller = ? or called = ?',$mobile,$mobile)->getCount('Id');
					if ($isRuning)
					{
						$err = "客服正在通话中..";
					}else if ($isAcct->web800->work_status != 1)
					{
						$err = "客服已经关闭通道";
					}else{
						$work_start = (str_replace(':', '', $isAcct->web800->work_start));
						$work_end = (str_replace(':', '', $isAcct->web800->work_end));
						
						if ($now >= $work_start && $now < $work_end)
						{
							$isone = Cbsubmit::find('bindname = ? and destination_number = ?',$isAcct->acctname, $mobile)->getCount('id');
							if($isone){
								$err = "存在此呼叫队列 请勿重复提交";
							}else{
								#检测次数
								Cbsubmit::call($isAcct->acctname, $mobile);
								$err = "请稍候。。。电话正在为您接通";
							}
						}else{
							$err = "不在工作时间";
						}
						
					}
					
				}
			}
		}else{
			
		}
		$this->_view['aid'] = $aid;
		$this->_view['flag'] = $isAcct->web800->work_status;
		$this->_view['err'] = $err;
		$this->_view['title'] = $isAcct->web800->work_title;
	}
	function actionweb800js()
	{
		$aid = intval($this->_context->aid);
		$this->_view['aid'] = $aid;
	}
	
	function actionqqhset()
	{
		$sipcode = intval($this->_context->sipcode);
		$num = trim($this->_context->num);
		$acctname = trim($this->_context->acctname);
		$acctname = Helper_Common::trim($acctname);
		$agent_id = Acctuser::find('acctname = ?',$acctname)->getOne();
		if ($agent_id->id() && Helper_Param::_call($num))
		{
			//Syslog::logs("机器人修改快号：{$sipcode}={$num}");
			QDB::getConn('fscall')->execute("call fscall.webacct_cbbindnum('{$acctname}','{$num}','{$sipcode}','qq')");
			QDB::getConn()->close();
			QDB::getConn()->connect();
			if ($sipcode == '-1')
			{
				$cbquick = Cbbind::find('acctname = ? and bindnum = ?',$acctname,$num)->order('sipnum desc')->getOne();
				$cblist = Cbnumlist::find('sipcode = ?',$cbquick->sipnum)->getOne();
			}else{
				$cblist = Cbnumlist::find('sipnum = ?',$sipcode)->getOne();
			}
			
			$this->_response(iconv('utf-8', 'gb2312', '尊敬的用户,您设置的亲情号为'.$cblist->sipnum.',绑定号码为'.$num.',请做好保存.'));
		}else{
			$this->_response(iconv('utf-8', 'gb2312', 'ERR:亲情号修改失败!'));
		}
		
	}
	/**
	 * 手机端WAP
	 */
	function actionacctwap()
	{
		$t = intval($this->_context->t);
		if (in_array($t, array(1,2,4,5,6,7)))
		{
			$aid = ($this->_context->aid);
			#如果是11手机号码则去查询代理ID
			if (strlen($aid) == 11)
			{
				$aid = Helper_Common::trim($aid);
				$u = Acctuser::find('acctname = ?',$aid)->getOne();
				
				if ($u->id())
				{
					$aid = $u->agent_id;
				}
			}
			$acct = Acct::find('id = ?',$aid)->getOne();
			
			if (!$acct->id())
			{
				$this->_response('');
				die;
			}
			$acctwap = Acctwapset::find('acctid = ?',$acct->id)->getOne();
			if (!$acctwap->acctid)
			{
				$this->_response('');
				die;
			}
			switch ($t)
			{
				case 1:
					$result = $acctwap->systitle_url;
					$this->_response($result);
					break;
				case 2:
					$result = $acctwap->shop_url;
					break;
						
				case 4:
					$result = $acctwap->hotcall_url;
					$this->_response($result);
					break;
				case 5:
					$result = $acctwap->smsmsg;
					$this->_response($result);
					die;
				case 6:
					$result = $acctwap->appname;
					$this->_response($result);
					die;
				case 7:
					$host = 'http://'.$_SERVER['HTTP_HOST'].'/';
					$result = $host.$acctwap->appimg;
					$this->_response($result);
					die;
				case 8:
					$host = 'http://'.$_SERVER['HTTP_HOST'].'/';
					$result = $host.$acctwap->androidimg;
					$this->_response($result);
					die;
			}
			header("location: {$result}");
			die;
		}else if ($t == 3){
			$aid = intval($this->_context->acctid);
				
			$acct = Acct::find('id = ?',$aid)->getOne();
			if (!$acct->id())
			{
				$this->_response('没有找到代理数据');
				die;
			}
			
			$mobile = trim($this->_context->mobile);
			$pwd = trim($this->_context->pwd);
			$acctwap = Acctwapset::find('acctid = ?',$acct->id)->getOne();
				
			if (!Helper_Param::_call($mobile))
			{
				$result = '手机号码格式不正确';
			}else if ($acctwap->open_reg == 1)
			{
				$result = '代理未打开注册';
			}else{
				$has = Acctuser::checkAcctname($mobile);
				if ($has->id())
				{
					$result = '手机已经开通';
				}else{
					$acctuser = new Acctuser();
					$acctuser->agent_id = $acct->id;
					$acctuser->admin_id = $acct->admin_id;
					
					$acctuser->acctname = $mobile;
					$acctuser->password = $pwd;
					$acctuser->balance = $acctwap->safe_money;
					$acctuser->activedate = date('Y-m-d');
					$acctuser->expireddays = $acctwap->expireddays;
					$acctuser->expireddate = date('Y-m-d',strtotime("{$acctuser->activedate} + {$acctuser->expireddays} day"));
					//$acctuser->bindexten_type = 0;
					//$acctuser->expireddays = $card->expireddays;
					$acctuser->rategroupid = $acctwap->rategroupid;
					$acctuser->rategroupid_acall = $acctwap->rategroupid_acall;
					$acctuser->limitbalance = 0;
					try {
						$acctuser->save(0,'create');
						$bind = new Userbindtel();
						$bind->admin_id = $acctuser->admin_id;
						$bind->agent_id = $acctuser->agent_id;
						$bind->acctname = $mobile;
						$bind->bindtel = $mobile;
						$bind->save(0,'create');//添加绑定号码
						//return true;
					} catch (Exception $e) {
						
					}
					$result = '0';
				}
				
			}
		}
		$this->_response($result);	
	}
	/**
	 * 一卡充值接口
	 */
	function actionecardpay()
	{

		//充值卡号
		$card = trim($this->_context->card);
		//充值密码
		$pwd = trim($this->_context->pwd);
		//手机号码
		$mobile = trim($this->_context->mobile);
		$mobile = Helper_Common::trim($mobile);
		//代理ID
		$aid = intval($this->_context->aid);
		if (!$card || !$mobile)
		{
			$result = '参数错误';
		}else{
		if(!Helper_Param::_call($mobile)){
			$result = '用户手机号码格式不正确';
		}else{
			//检测用户
			$acctuser = Acctuser::find('acctname = ?',$mobile)->getOne();
			if (!$acctuser->id())
			{
				$result = '不存在用户';
			}else{
				$wapset = Acctwapset::find('acctid = ?',$acctuser->agent_id)->getOne();
				if (!$wapset->acctid)
				{
					$result = '代理未设置充值渠道';
				}else if(!($wapset->e_appid) || !($wapset->e_appkey)) {
						
					$result = '代理未设置充值渠道';
				}else{
					//只能存在的用户
					$aid = $acctuser->agent_id;
					//开始产生订单号
					//$p2_Order =
					#商家设置用户购买商品的支付信息.
					#商户订单号.提交的订单号必须在自身账户交易中唯一.
					$p2_Order			= sprintf('%s%s%s',date('YmdHis'),substr(time(), -4),$acctuser->id);;
					#支付卡面额
					$p3_Amt				= 500;
					#是否较验订单金额
					$p4_verifyAmt		= 'false';
					#产品名称
					$p5_Pid				= 'mobilecard';
					#iconv("UTF-8","GBK//TRANSLIT",$_POST['p5_Pid']);
					#产品类型
					$p6_Pcat			= 'mobilecard';
					#iconv("UTF-8","GBK//TRANSLIT",$_POST['p6_Pcat']);
					#产品描述
					$p7_Pdesc			= '';
					#iconv("UTF-8","GBK//TRANSLIT",$_POST['p7_Pdesc']);
					#商户接收交易结果通知的地址,易宝支付主动发送支付结果(服务器点对点通讯).通知会通过HTTP协议以GET方式到该地址上.
					$p8_Url				= 'http://'.$_SERVER['HTTP_HOST'].'/interface/ecardback/aid/'.$aid;
					#临时信息
					$pa_MP				= '';
					#iconv("UTF-8","GB2312//TRANSLIT",$_POST['pa_MP']);
					#卡面额
					$pa7_cardAmt			= 500;
					#支付卡序列号.
					$pa8_cardNo			= $card;
					#支付卡密码.
					$pa9_cardPwd			= $pwd;
					#支付通道编码
					$pd_FrpId			= 'SZX' ;
					#应答机制
					$pr_NeedResponse		= "1";
					#用户唯一标识
					$pz_userId			= $mobile;
					#用户的注册时间
					$pz1_userRegTime		= $acctuser->activedate;
					$result = Helper_Ecard::annulCard($wapset->e_appid,$wapset->e_appkey,$p2_Order,$p3_Amt,$p4_verifyAmt,$p5_Pid,$p6_Pcat,$p7_Pdesc,$p8_Url,$pa_MP,$pa7_cardAmt,$pa8_cardNo,$pa9_cardPwd,$pd_FrpId,$pz_userId,$pz1_userRegTime);
					Helper_Ecard::addEcardLog($p2_Order, $p8_Url, $pa8_cardNo, $pa9_cardPwd, $mobile);
					#dump($result);
					Helper_Common::log("ecardback result  {$pa8_cardNo}: " . print_r($result,true));
					$this->_response('1');
					
				}
				
				}	

			}
		}
		
		$this->_response($result);
		
	}
	/**
	 * 一卡充值回调
	 */
	function actionecardback()
	{
			ignore_user_abort(true);
	        Helper_Common::log("ecardback request : " . print_r($_REQUEST,true));
	        Q::changeIni('runtime_response_header', false);
	        if (!isset($_REQUEST['r0_Cmd']) || !isset($_REQUEST['r1_Code']))
	        {
	        	exit('success');
	        }
	        $r0_Cmd = $_REQUEST['r0_Cmd'];
			$r1_Code = $_REQUEST['r1_Code'];
			$p1_MerId = $_REQUEST['p1_MerId'];
			$p2_Order = $_REQUEST['p2_Order'];
			$p3_Amt = $_REQUEST['p3_Amt'];
			$p4_FrpId = $_REQUEST['p4_FrpId'];
			$p5_CardNo = $_REQUEST['p5_CardNo'];
			$p6_confirmAmount = $_REQUEST['p6_confirmAmount'];
			$p7_realAmount = $_REQUEST['p7_realAmount'];
			$p8_cardStatus = $_REQUEST['p8_cardStatus'];
			$p9_MP = $_REQUEST['p9_MP'];
			$pb_BalanceAmt = $_REQUEST['pb_BalanceAmt'];
			$pc_BalanceAct = $_REQUEST['pc_BalanceAct'];
			$hmac = $_REQUEST['hmac'];
	        #	解析返回参数.
// 	        $return = Helper_Ecard::getCallBackValue($r0_Cmd,$r1_Code,$p1_MerId,$p2_Order,$p3_Amt,$p4_FrpId,$p5_CardNo,$p6_confirmAmount,$p7_realAmount,$p8_cardStatus,
// 	        $p9_MP,$pb_BalanceAmt,$pc_BalanceAct,$hmac);
	        $aid = intval($this->_context->aid);
	        $wapset = Acctwapset::find("acctid = ?",$aid)->getOne();
	        if ($wapset->acctid)
	        {
	        	#	判断返回签名是否正确（True/False）
	        	$bRet = Helper_Ecard::CheckHmac($wapset->e_appkey,$r0_Cmd,$r1_Code,$p1_MerId,$p2_Order,$p3_Amt,$p4_FrpId,$p5_CardNo,$p6_confirmAmount,$p7_realAmount,$p8_cardStatus,
	        	$p9_MP,$pb_BalanceAmt,$pc_BalanceAct,$hmac);
	        	#	以上代码和变量不需要修改.
	        	 
	        	#	校验码正确.
	        	if($bRet){
	        	
	        		#在接收到支付结果通知后，判断是否进行过业务逻辑处理，不要重复进行业务逻辑处理
	        		if($r1_Code=="1"){
// 	        		echo "<br>支付成功!";
// 	        		echo "<br>商户订单号:".$p2_Order;
// 	        			echo "<br>支付金额:".$p3_Amt;
						$ecard = Ecard::find('orderid = ? and status = 0 and add_status = 0',$p2_Order)->getOne();
						if ($ecard->orderid)
						{
							$acctname = trim($ecard->acctname);
							$acctuser = Acctuser::checkAcctname($acctname);
							if (!$acctuser->id())
							{
								Helper_Common::log('NOT FIND USER acctname='.$acctname);
							}else{
								
								#给用户加钱
								try {
									$balance = $acctuser->balance;
									$acctuser->balance += $p3_Amt;
									$acctuser->expireddays += 60;
									$acctuser->expireddate = date('Y-m-d',strtotime("+60 day",strtotime($acctuser->expireddate)));
									$acctuser->save(0,'update');
									#更新订单记录
									$ecard->status = 1;
									$ecard->add_status = intval($p3_Amt);
									$ecard->callbacktime = time();
									$ecard->cardamt = $p3_Amt;
									$ecard->save(0,'update');
									#添加充值记录
									$log = new Voucherlog();
									$log->acctname = $acctuser->acctname;
									$log->admin_id = $acctuser->admin_id;
									$log->agent_id = $acctuser->agent_id;
									$log->voucher_guid = $ecard->cardno;
									$log->voucher_password = substr($ecard->cardpwd, 0,strlen($ecard->cardpwd)-4).'****';
									$log->voucher_balance = $p3_Amt;
									$log->voucher_prebalance = $balance;
									$log->voucher_acctname = $acctuser->acctname;
									$log->voucher_paylimitday = '-1';
									$log->save(0,'create');
									Helper_Common::log('SUCCESS:'.print_r($_REQUEST,true));
								} catch (Exception $e) {
								}
							}
						}else{
							#不存在订单
							Helper_Common::log('NOT FIND ORDERID='.$p2_Order);
						}
	        			exit('success');
	        		} else if($r1_Code=="2"){
	        			$ecard = Ecard::find('orderid = ? and status = 0 and add_status = 0',$p2_Order)->getOne();
	        			if ($ecard->orderid)
	        			{
	        				$ecard->status =2;
	        				$ecard->save(0,'update');
	        			}
// 	        			echo "<br>支付失败!";
// 	        			echo "<br>商户订单号:".$p2_Order;
	        			
	        	}
	        	} else{
	        		 #效验错误
	        		Helper_Common::log($p2_Order."=sign error");
// 	        		$sNewString = getCallbackHmacString($r0_Cmd,$r1_Code,$p1_MerId,$p2_Order,$p3_Amt,
// 	        		$p4_FrpId,$p5_CardNo,$p6_confirmAmount,$p7_realAmount,$p8_cardStatus,$p9_MP,$pb_BalanceAmt,$pc_BalanceAct);
// 	        		echo "<br>localhost:".$sNewString;
// 	        		echo "<br>YeePay:".$hmac;
// 	        		echo "<br>交易签名无效!";
// 	        		exit;
	        		
	        		}
	        }else{
	        	
	        	
	        }
	        
	        
	        exit('success');
	        
	}
	
	function actionchecklogin()
	{
		$mobile = $this->_context->get('mobile');
		$mobile = Helper_Common::trim($mobile);
    	$pwd = $this->_context->get('pwd');
    	if (!Helper_Param::_phone($mobile))
    	{
    		$result = '2';
    	}else
    	{
    		$user = Acctuser::checkAcctname($mobile);
    		//$bind = Userbindtel::find('bindtel = ?',$mobile)->setColumns('id,acctname')->getOne();
    		if(!$user->id() )
    		{
    			$result = '2';
    		}else if($user->password !== $pwd)
    		{
    			$result = '1';
    		}
    		else{
    			$result = '0';
    		}
    	}
    	$this->_response($result);
	}
	
	function actionBalanceNoPwd()
	{
		$mobile = $this->_context->get('mobile');
		$mobile = Helper_Common::trim($mobile);
		$result = array(
			'errcode'=>1,
			'errmsg'=>'',
			'userinfo'=>array('mobile'=>$mobile,'balance'=>0,'expireddate'=>'2000-01-01')
		);
    	if (!Helper_Param::_phone($mobile))
    	{
    		$result['errcode']=2;
    		$result['errmsg']='手机号码格式不正确';
    	}else
    	{
    		$user = Acctuser::checkAcctname($mobile);
    		//$bind = Userbindtel::find('bindtel = ?',$mobile)->setColumns('id,acctname')->getOne();
    		if(!$user->id() )
    		{
    			$result['errcode']=3;
    			$result['errmsg']='用户不存在';
    		}else{
    			$result['errcode']=0;
    			$result['errmsg']='查询成功';
    			$result['userinfo']['balance'] = floatval(sprintf('%f',isset($user->balance)?floatval($user->balance):0));
    			$result['userinfo']['expireddate'] = $user->expireddate;
    		}
    	}
    	exit(json_encode($result));
	}
	
	/**
	 * 兑换积分
	 */
	function actionuploadscore()
	{
		$mobile = trim($this->_context->mobile);
		$mobile = Helper_Common::trim($mobile);
		$score = intval($this->_context->score);
		$time = trim($this->_context->time);
		$sign = trim($this->_context->sign);
		$result = array('code'=>1,'msg'=>'兑换失败');
		$mesign = sprintf('%s%s%s%s',$mobile,$score,$time,'7fa3f69d91e521942338d73a636ccc42');
		if(!$mobile  || !$time || !$sign)
		{
			exit(json_encode($result));
		}
		
		if (md5($mesign) == $sign)
		{
			$acctuser = Acctuser::checkAcctname($mobile);
			if (!$acctuser->id())
			{
				$result['msg'] = '用户不存在';
			}else{
				$wap = Acctwapset::find('acctid = ?',$acctuser->agent_id)->getOne();
				$scoreset = 0.02;
				if($wap->id())
				{
					$scoreset = floatval($wap->user_scoreset);
				}
				$money = floatval($scoreset*$score);
				$flag = Acctuser::addmoney($acctuser->acctname, $money);
				if ($flag)
				{
					$addlog = new Wapscorelog();
					$addlog->admin_id = $acctuser->admin_id;
					$addlog->agent_id = $acctuser->agent_id;
					$addlog->acct_id = $acctuser->id;
					$addlog->acctname = $acctuser->acctname;
					$addlog->money = $money;
					$addlog->type = 0;
					$addlog->created=time();
					$addlog->score = abs($score);
					
					$addlog->save();
					$agent_set = 0.02;
					Wapscorelog::addAgent($acctuser->agent_id, $score, $agent_set);
					$result['code'] = 0;
					$result['msg'] = '成功兑换:'.$money;
				}else{
					$result['msg'] = '转换余额出错';
				}
			}
		}else{
			$result['msg'] = '加密错误';
		}
		exit(json_encode($result));
	}
	
	function actionscorelist()
	{
		$mobile = trim($this->_context->mobile);
		$mobile = Helper_Common::trim($mobile);
		//$pwd = trim($this->_context->pwd);
		$page = intval($this->_context->page);
		$pagenum = intval($this->_context->pagenum);
		$result = array(
					'code'=>1,
					'msg'=>'查询失败',
					'page'=>$page,
					'pagenum'=>$pagenum,
					'pagecount'=>0,
					'data'=>null
				);
		$acctuser = Acctuser::find('acctname = ? ',$mobile)->getOne();
		if(!$acctuser->id())
		{
			$result['msg']='用户账号密码不正确';
		}else{
			$count = Wapscorelog::find('acct_id = ? and type = 0',$acctuser->id)->getCount('id');
			$data = Wapscorelog::find('acct_id = ? and type = 0',$acctuser->id)->limitPage($page,$pagenum)->getAll();
			$result['code']=0;
			$result['msg']='查询成功';
			$result['pagecount']=ceil($count/$pagenum);
			if($result['pagecount']<$page)
			{
				$result['code']=1;
				$result['msg']='超出总页数';
			}
			foreach ($data as $item)
			{
				
				$result['data'][] = array(
							'id'=>$item->id,
							'time'=>date('Y-m-d H:i:s',$item->created),
							'score'=>$item->score,
							'money'=>floatval($item->money)
						);
			}
		}
		exit(json_encode($result));
	}
	/**
	 * 代理开通用户VIP
	 * Enter description here ...
	 */
	function actionagentvips()
	{
			$mobile = trim($this->_context->mobile);
			$mobile = Helper_Common::trim($mobile);
		#0 =kai 1=guan
		$flag = intval($this->_context->flag);
		//$acctid = intval($this->_context->acctid);
		//$acctuser = Acctuser::find(array_merge($this->_format_appendSql(),array('id'=>$acctid)))->getOne();
		$time = trim($this->_context->time);
		$sign = trim($this->_context->sign);
		$result = array('code'=>1,'msg'=>'请求失败');
		$mesign = sprintf('%s%s%s',$mobile,$time,'e96c29eb0567bec55559446c8602119c');
		if(!$mobile ||  !$time || !$sign)
		{
			exit(json_encode($result));
		}
		if (md5($mesign) == $sign)
		{
			$acctuser = Acctuser::checkAcctname($mobile);
			if (!$acctuser->id())
			{
				$result['msg'] = '用户不存在';
			}else
			{
				if ($flag == 0)
				{
					QDB::getConn()->execute("call fscall.acct_vippay('{$acctuser->acctname}',0)");
					QDB::getConn()->close();
					$result['code'] = 0;
					$result['msg'] = '开通成功';
						
				}else{
					QDB::getConn()->execute("call fscall.acct_vippay('{$acctuser->acctname}',1)");
					QDB::getConn()->close();
					$result['code'] = 0;
					$result['msg'] = '关闭成功';
				}
			}
		}else{
			$result['msg'] = '效验错误';
		}
		exit(json_encode($result));
	}
	/**
	 * 开通VIP
	 */
	function actionvips()
	{
		$mobile = trim($this->_context->mobile);
		$mobile = Helper_Common::trim($mobile);
		#0 =kai 1=guan
		$flag = intval($this->_context->flag);
		//$acctid = intval($this->_context->acctid);
		//$acctuser = Acctuser::find(array_merge($this->_format_appendSql(),array('id'=>$acctid)))->getOne();
		$time = trim($this->_context->time);
		$sign = trim($this->_context->sign);
		$result = array('code'=>1,'msg'=>'请求失败');
		$mesign = sprintf('%s%s%s',$mobile,$time,'7fa3f69d91e521942338d73a636ccc42');
		if(!$mobile ||  !$time || !$sign)
		{
			exit(json_encode($result));
		}
		if (md5($mesign) == $sign)
		{
			$acctuser = Acctuser::checkAcctname($mobile);
			if (!$acctuser->id())
			{
				$result['msg'] = '用户不存在';
			}else
			{
				if ($flag == 0)
				{
					QDB::getConn()->execute("call fscall.acct_vippay('{$acctuser->acctname}',0)");
					QDB::getConn()->close();
					$result['code'] = 0;
					$result['msg'] = '开通成功';
						
				}else{
					QDB::getConn()->execute("call fscall.acct_vippay('{$acctuser->acctname}',1)");
					QDB::getConn()->close();
					$result['code'] = 0;
					$result['msg'] = '关闭成功';
				}
			}
		}else{
			$result['msg'] = '效验错误';
		}
		exit(json_encode($result));
	}
	/**
	 * 查询代理设置的VIP费用
	 */
	function actionagentvipmoney()
	{
		$mobile = trim($this->_context->mobile);
		$mobile = Helper_Common::trim($mobile);
		$result = array('code'=>1,'msg'=>'查询失败','vipmoney'=>0);
		$acctuser = Acctuser::checkAcctname($mobile);
		if (!$acctuser->id()){
			$result['msg'] = '用户不存在';
		}else{
			$vip = Acctsetting::find('agent_id = ? ',$acctuser->agent_id)->getOne();
			if (!$vip->id())
			{
				$result['code'] = 0;
				$result['msg'] = '查询成功';
				$result['vipmoney'] = 1;
			}else{
				$result['code'] = 0;
				$result['msg'] = '查询成功';
				$result['vipmoney'] = floatval($vip->vipmoney);
			}
		}
		exit(json_encode($result));
	}
	/**
	 * 查询用户VIP
	 */
	function actiongetuservip()
	{
		$mobile = trim($this->_context->mobile);
		$mobile = Helper_Common::trim($mobile);
		$result = array('code'=>0,'msg'=>'查询成功');
		$acctid = Acctuser::find('acctname = ?',$mobile)->setColumns('id')->getOne();
		
		if($acctid->id())
		{
			$isvip = Acctuservip::find('acct_id = ? and acctname = ? and expdate >=?',$acctid->id,$mobile,date('Y-m-d'))->getCount('id');
			if($isvip)$result['code'] = 1;
		}
		exit(json_encode($result));
	}
	/**
	 * 认证主叫
	 */
	function actioninsertauth()
	{
			$acctname = trim($this->_context->mobile);
			$acctname = Helper_Common::trim($acctname);
			$pwd = trim($this->_context->pwd);
			$acctuser = Acctuser::find('acctname = ? and password = ?',$acctname,$pwd)->getOne();
			if($acctuser->id())
			{
				if(strlen($acctuser->bindtel)>3)
				{
					$result = array('code'=>3,'msg'=>'您的号码已经通过验证，系统无需再回另验证');
				}else{
					$num = Acctuser::insertAuth($acctname);
					if($num<=2)
					{
						$result = array('code'=>2,'msg'=>'系统将验证码通过语音方式播放到本手机，听到验证码后请输入一次后完成验证，该功能免费!');
					}else{
						$result = array('code'=>0,'msg'=>'发起成功,请等待回铃');
					}
				}
				
			}else{
				$result = array('code'=>1,'msg'=>'用户不存在');
			}
			exit(json_encode($result));
	}
	/**
	 * 淘宝88系统
	 */
	function actiontaobao88()
	{


		$result = '';
		$session = $this->_loadtoken();
		if($session == '')
		{
			$result = '上级未设置TOKEN';
			$this->_view['result'] = $result;
			return ;
		}
		if(isset($_REQUEST['orderid']) && isset($_REQUEST['acctname']))
		{
			$rnd  = $this->_context->get('rndcode');
			if (!Helper_Ckcode::check($rnd)){
				return $this->_redirectMessage('失败', '验证码错误', ('/interface/taobao88'));
				exit;
			}
			require_once '../lib/top/TopClient.php';
			require_once '../lib/top/request/TradeFullinfoGetRequest.php';
			require_once '../lib/top/request/LogisticsDummySendRequest.php';
			require_once  '../lib/top/RequestCheckUtil.php';
			$orderid = trim($this->_context->orderid);
			$acctname = trim($this->_context->acctname);
			$querypwd = md5(time().$acctname.$orderid);
			$bind = trim($this->_context->bind);
			$acct = Acct::find('acctname = ?',$acctname)->getOne();
			if(!$acct->id() || $acct->is_Onelevel == false)
			{
				$result = '代理不存在或者1级代理使用';
				$this->_view['result'] = $result;
				return ;
			}
			if($acct->taobao_flag == 1)
			{
				$result = '已经设置后台自动充值,不能手动操作,,如需要取消或者更换淘宝账号请先关闭自动充值再重新绑定!';
				$this->_view['result'] = $result;
				return ;
			}
			$c = new TopClient;
			$c->appkey = '21612259';
			$c->secretKey = '39a31b83172056116d82ac8af7ad7a4b';
			
			$req = new TradeFullinfoGetRequest;
			$req->setFields("status,num,total_fee,price,buyer_nick");
			$req->setTid($orderid);
			$querytaobao = $c->execute($req, $session);
			#$resp->trade->num
			if($querytaobao->trade->status == 'WAIT_SELLER_SEND_GOODS')
			{
				$req = new LogisticsDummySendRequest();
				$req->setTid($orderid);
				$resp = $c->execute($req,$session);
				if($resp->shipping->is_success){
					Helper_Common::log("TAOBAO SEND OK,ORDERDATA=".print_r($querytaobao,true),'taobao_web');
					$cardinfo = '';
					for ($i=1;$i<=$querytaobao->trade->num;$i++)
					{
						$card = array(
								'cardname'=>$orderid.'_'.$i,
								'password'=>$querypwd,
								'balance' =>$querytaobao->trade->price,
								'voucher_acctname'=>'',
								'vouchered_acctname'=>'',
								'vouchereddate'=>'0000-00-00',
								'agent_id'=> -1,
								'create_acctname'=>'taobao'
						);
						//$cardinfo .= sprintf("%s,%s<br>",$orderid.'_'.$i,$querypwd);
						Acct::make_agentcard($card);
						$status = Acct::use_agentcard($acct->id, $card['cardname'], $card['password']);
						if ($status === true)
						{
							$acct_name = $acct->acctname;
							$log = new Syslog();
							$log->acctname = $acct_name;
							$log->admin_id = 1;
							$log->agent_id = $acct->id;
							$log->clientip = $_SERVER['REMOTE_ADDR'];
							$log->logtext = "使用淘宝代理充值卡{$card['cardname']} 为 {$acct_name} 充值{$card['balance']}成功";
							$log->save(0,'create');
							
						}
					}
					#绑定淘宝
					if($bind)
					{
						$acct->taobao_flag = 1;
					    $acct->buyer_nick = $querytaobao->trade->buyer_nick;
					    $acct->save(0,'update');
					}
					#验证成功
					//$card = Taobaocard::find("used = 0 and type = '88' and price = ? ",$querytaobao->trade->price)->limit(0,$querytaobao->trade->num)->query();
					//Helper_Common::log("DATA LOG:".print_r($card,true));
// 					foreach ($card as $i=>$v)
// 					{
// 						$v->used = 1;
// 						$v->orderid = $orderid;
// 						$v->acctname = $acctname;
// 						$v->querypwd = $querypwd;
// 						$v->usetime = date('Y-m-d H:i:s');
// 						$v->save();
// 						$result .= sprintf("%s,%s<br>",$v->cardname,$v->cardpwd);
// 					}
					$result = '充值成功,可在充值记录查询,并且请在淘宝确认收货!';
					//$result = "验证成功,$orderid 订单产生如下卡号,卡密:<br>".$result;
					//$result =  $result."<br>此次查询密码为:$querypwd,请复制方便以后查询使用.";
					//exit;
				}
				
			}else{
				$result = '订单状态错误';
//				exit("订单状态错误");
			}
		
		}
		$this->_view['result'] = $result;
	}
	function actiontaobao11()
	{
		$result = '';
		$session = $this->_loadtoken();
		if($session == '')
		{
			$result = '上级未设置TOKEN';
			$this->_view['result'] = $result;
			return ;
		}
		if(isset($_REQUEST['orderid']) && isset($_REQUEST['acctname']))
		{
			$rnd  = $this->_context->get('rndcode');
			if (!Helper_Ckcode::check($rnd)){
				$result='验证码错误!';
				$this->_view['result'] = $result;
				return;
// 				return $this->_redirectMessage('失败', '验证码错误', ('/interface/taobao11'));
// 				exit;
			}
			require_once '../lib/top/TopClient.php';
			require_once '../lib/top/request/TradeFullinfoGetRequest.php';
			require_once '../lib/top/request/LogisticsDummySendRequest.php';
			require_once  '../lib/top/RequestCheckUtil.php';
			$orderid = trim($this->_context->orderid);
			$acctname = trim($this->_context->acctname);
			$querypwd = md5(time().$acctname.$orderid);
			try {
				
			} catch (Exception $e) {
			}	
			$c = new TopClient;
			$c->appkey = '21612259';
			$c->secretKey = '39a31b83172056116d82ac8af7ad7a4b';
				
			$req = new TradeFullinfoGetRequest;
			$req->setFields("status,num,total_fee,price");
			$req->setTid($orderid);
			$querytaobao = $c->execute($req, $session);
			#$resp->trade->num
			if($querytaobao->trade->status == 'WAIT_SELLER_SEND_GOODS')
			{
			    $card = Taobaocard::find("used = 0 and type = '11' and price = ? ",$querytaobao->trade->price)->limit(0,$querytaobao->trade->num)->query();
				if(count($card) != $querytaobao->trade->num)
				{
				    $result='充值卡池余卡不够,请联系管理员!';
				    $this->_view['result'] = $result;
				    return;
				}
			    $req = new LogisticsDummySendRequest();
				$req->setTid($orderid);
				$resp = $c->execute($req,$session);
				if($resp->shipping->is_success){
					Helper_Common::log("TAOBAO SEND OK,ORDERDATA=".print_r($querytaobao,true),'taobao_web');
						
					#验证成功
					
					Helper_Common::log("DATA LOG:".print_r($card,true));
					foreach ($card as $i=>$v)
					{
					$v->used = 1;
					$v->orderid = $orderid;
					$v->acctname = $acctname;
					$v->querypwd = $querypwd;
					$v->usetime = date('Y-m-d H:i:s');
					$v->save();
					$result .= sprintf("%s,%s<br>",$v->cardname,$v->cardpwd);
					}
					$result = "验证成功,$orderid 订单产生如下卡号,卡密:<br>".$result;
					$result =  $result."<br>请牢记账号和订单号,方便查询记录,请复制方便以后查询使用.";
					//exit;
				}
		
				}else{
				$result="订单状态错误";
				}
		
			}
			$this->_view['result'] = $result;
	}
	function actiontaobaohistory()
	{
		$result = '';
		if(isset($_REQUEST['acctname']) && isset($_REQUEST['orderid']))
		{
			$rnd  = $this->_context->get('rndcode');
			if (!Helper_Ckcode::check($rnd)){
				return $this->_redirectMessage('登陆失败', '验证码错误', ('/interface/taobaohistory'));
				exit;
			}
			$acctname = trim($this->_context->acctname);
			$orderid = trim($this->_context->orderid);
			$type = trim($this->_context->type);
			switch ($type)
			{
				case 0:
					$types = '88';
					break;
				case 1:
					$types = '11';
					break;
				default:
					$types = '88';
					break;
			}
			$card = Taobaocard::find('type = ? and orderid = ? and acctname = ?',$types,$orderid,$acctname)->getAll();
			if(count($card))
			{
				$cardinfo = '';
				foreach ($card as $k=>$v)
				{
					$cardinfo .= sprintf("%s,%s<br>",$v->cardname,$v->cardpwd);
				}
				$result = "查询订单:{$orderid} 对应的卡号如下：<br>".$cardinfo;
			}else{
				$result = '没有找到信息';
			}
			
		}
		$this->_view['result'] = $result;
	}
	//升级为加密呼叫
	function actionSetPwdCall()
	{
		$mobile = trim($this->_context->mobile);
		$mobile = Helper_Common::trim($mobile);
		$pwd = trim($this->_context->pwd);
		$flag = intval($this->_context->flag);
		$result = array('status'=>1,'msg'=>'用户名或密码错误');
		$acctuser = Acctuser::find("acctname = ? and password = ?",$mobile,$pwd)->setColumns('id,callpwd')->getOne();
		if(!in_array($flag, array(0,1)))
		{
			$result = array('status'=>2,'msg'=>'参数错误');
		}
		if ($acctuser->id())
		{
			$result['status'] = 0;
			$result['设置成功'];
			$acctuser->callpwd = intval($flag);
			$acctuser->save();
		}
		exit(json_encode($result));
	}
	function actionfindPwdTosms()
	{
		$mobile = trim($this->_context->mobile);
		$mobile = Helper_Common::trim($mobile);
		$ip = Helper_Common::get_ip();
		$result = array('code'=>-1,'msg'=>'');
		$acctuser = Acctuser::find('acctname = ?',$mobile)->getOne();
		if ($acctuser->id())
		{
			$isDisbale = Findpwdlog::find('userid = ? and date = ?',$acctuser->id,date('Y-m-d'))->getOne();
			if($isDisbale->id())
			{
				$result['code'] = 2;
				$result['msg'] = '每日只能获取密码短信1次';
			}else{
				$result['code'] = 0;
				$result['msg'] = '成功';

				$isDisbale->userid = $acctuser->id;
				$isDisbale->date = date('Y-m-d');
				$isDisbale->ip = $ip;
				$isDisbale->save(0,'create');
				if($acctuser->agent->smsurl  && $acctuser->agent->smsflag)
				{
					$msg = "($mobile)您当前的密码为:{$acctuser->password},请妥善保管,每日只能使用此功能1次.";
					//$msg = $acctuser->acctname.",您此次清除用户数据的操作验证码为:".$rnd.",请尽快使用.";
					$msglength = mb_strlen($msg,'UTF-8');
					$msg = urlencode($msg);
					$url = str_replace('%m%', $mobile, $acctuser->agent->smsurl);
					$url = str_replace('%s%', $msg, $url);
					$result = Helper_Common::cget($url);
					QLog::log('smssend:'.$url.'|'.$result);
					$result = iconv("GB2312","UTF-8",$result);
					QDB::getConn()->execute("call smscost({$acctuser->agent->id},0.01)");
				}
			}
		}else{
			$result['code'] = -1;
			$result['msg'] = '用户不存在';
		}
		exit(json_encode($result));
	}
	function actionVoipAuthBySms()
	{
	    $mobile = trim($this->_context->mobile);
	    $mobile = Helper_Common::trim($mobile);
	    $pwd = trim($this->_context->pwd);
		$ip = Helper_Common::get_ip();
		$result = array('code'=>-1,'msg'=>'');
		$acctuser = Acctuser::find('acctname = ? and password = ?',$mobile,$pwd)->getOne();
		if($acctuser->id())
		{
		    if($acctuser->bind_ipphone)
		    {
		        $result['code'] = 1;
			    $result['msg'] = '已经认证过主叫号码';
		    }else{
		        $allcount = Smsvoipauth::find('userid = ?',$acctuser->id)->getCount('id');
		        if($allcount >=10)
		        {
    		        $result['code'] = 2;
    			    $result['msg'] = '最多使用10次此功能';
		        }else{
		            $daycount = Smsvoipauth::find('userid = ? and date = ?',$acctuser->id,date('Y-m-d'))->getCount('id');
		            if($daycount>=3)
		            {
		                $result['code'] = 3;
    			        $result['msg'] = '每日限制次数3次';
		            }else{
		                $result['code'] = 0;
				        $result['msg'] = '成功';
		                $code = mt_rand(100000, 999999);
		                $log = new Smsvoipauth();
		                $log->userid = $acctuser->id;
		                $log->code = $code;
		                $log->date = date('Y-m-d');
		                $log->ip = $ip;
		                $log->save(0,'create');
    		            if($acctuser->agent->smsurl  && $acctuser->agent->smsflag)
    				    {
        					$msg = "($mobile)您本次的主叫验证码为:{$code},请尽快保管,每日只能使用此功能3次,总计10次.";
        					//$msg = $acctuser->acctname.",您此次清除用户数据的操作验证码为:".$rnd.",请尽快使用.";
        					$msglength = mb_strlen($msg,'UTF-8');
        					$msg = urlencode($msg);
        					$url = str_replace('%m%', $mobile, $acctuser->agent->smsurl);
        					$url = str_replace('%s%', $msg, $url);
        					$smsresult = Helper_Common::cget($url);
        					
        					QLog::log('smssend:'.$url.'|'.$smsresult);
        					$smsresult = iconv("GB2312","UTF-8",$smsresult);
        					QDB::getConn()->execute("call smscost({$acctuser->agent->id},0.01)");
    				    }
		            }
		        }
		    }
		}else{
		    $result['code'] = -1;
			$result['msg'] = '用户不存在';
		}
		exit(json_encode($result));
	}
	
	function actionVoipAuthBySmsSubmit()
	{
	    $mobile = trim($this->_context->mobile);
	    $mobile = Helper_Common::trim($mobile);
	    $pwd = trim($this->_context->pwd);
	    $code = trim($this->_context->code);
		$ip = Helper_Common::get_ip();
		$result = array('code'=>-1,'msg'=>'');
		$acctuser = Acctuser::find('acctname = ? and password = ?',$mobile,$pwd)->getOne();
		if($acctuser->id())
		{
		     if($acctuser->bind_ipphone)
		    {
		        $result['code'] = 1;
			    $result['msg'] = '已经认证过主叫号码';
		    }else{
		        $log = Smsvoipauth::find('userid = ?',$acctuser->id)->order('id desc')->getOne();
		        if($log->id())
		        {
    		        if($log->submitcount >= 3)
    		        {
    		            $result['code'] = 3;
    			        $result['msg'] = '输入错误,最多尝试3次';
    		        }else if($code == $log->code)
    		        {
    		            $acctuser->bind_ipphone = $acctuser->acctname;
    		            $acctuser->save(0,'update');
    		            $log->updatetime = date('Y-m-d H:i:s');
    		            $log->result = $acctuser->acctname;
    		            $log->save(0,'update');
    		            $result['code'] = 0;
    			        $result['msg'] = '成功';
    		        }else{
    		            $log->submitcount += 1;
    		            $log->save(0,'update');
    		            $result['code'] = 4;
    			        $result['msg'] = '输入错误,还有'.(3-$log->submitcount).'次机会';
    		        }
		        }else{
		                $result['code'] = 2;
    			        $result['msg'] = '请先获取短信验证码';
		        }
		    }
		}else{
		    $result['code'] = -1;
			$result['msg'] = '用户不存在';
		}
		exit(json_encode($result));
	}
	function actiongetpackage()
	{
		$agent_id = intval($this->_context->agent_id);
		$data = Acctpackage::find('agent_id = ?',$agent_id)->setColumns('id,packagename')->asArray()->getAll();
		$result = '';
		$result = '<option value="0">不使用套餐</option>';
		foreach ($data as $k=>$v)
		{
			$result.= '<option value="'.$v['id'].'">'.$v['packagename'].'</option>';
		}
		exit($result);
	}
	function actionchangeusername()
	{
	    $acctname = trim($this->_context->acctname);
	    $acctname = Helper_Common::trim($acctname);
	    $pwd = trim($this->_context->pwd);
	    $newname = trim($this->_context->newname);
	    $newname = Helper_Common::trim($newname);
	    if (!$newname){
	        exit('1');
	    }else{
	        $checknew = Acctuser::checkAcctname($newname);
	        if ($checknew->id())
	        {
	            exit('1');
	        }
	        $acctuser = Acctuser::find('acctname = ?',$acctname)->getOne();
	        if (!$acctuser->id())
	        {
	            exit('1');
	        }else if($acctuser->password !== $pwd)
	        {
	               exit('1');
	        }else{
	            User_Safelog::log($acctuser->id, 1, 0,$acctuser->acctname,$newname);
	            $acctuser->acctname = $newname;
	            $acctuser->save(0,'update');
	            Syslog::notloginlogs("ID:{$acctuser->id} {$acctname} 修改帐号为:{$newname}");
	            exit('0');
	        }
	    }
	    exit('1');
	}
	
	function actionchangeusernamelog()
	{
	    $acctname = trim($this->_context->acctname);
	    $acctname = Helper_Common::trim($acctname);
	    $tar_acctname = trim($this->_context->tar_acctname);
	    $where = new QDB_Cond();
	    if ($acctname)
	    {
	        $where->andCond('op_arg1 = ?',$acctname);
	    }
	    if ($tar_acctname)
	    {
	        $where->andCond('op_arg2 = ?',$tar_acctname);
	    }
	    $list = User_Safelog::find($where)->asArray()->getAll();
	    $result = array(
	        'code'=>0,
	        'data'=>array()
	    );
	    foreach ($list as $k=>$v)
	    {
	        $result['data'][] = array('oldname'=>$v['op_arg1'],'newname'=>$v['op_arg2'],'date'=>date('Y-m-d H:i:s',$v['created']));
	    }
	    exit(json_encode($result));
	}
	function actionwx()
	{
		Helper_Common::log(print_r($request,true));
	    $acctname = trim($this->_context->acctname);
	    $acctname = Helper_Common::trim($acctname);
	    if(!$acctname)
	    {
	        die;
	    }
	    $acct = Acct::find('acctname = ?',$acctname)->setColumns('id')->getOne();
	    if (!$acct->id())
	    {
	        die;
	    }
	    $wapset = Acctwapset::find('acctid = ?',$acct->id)->setColumns('wxname,wxtoken')->getOne();
	    if(isset($_GET['echostr']) && $_GET['echostr'])
	    {
	        $make = sha1(sprintf("%s%s%s",$wapset->wxtoken,$this->_context->timestamp,$this->_context->nonce));
	        if (1)
	        {
	            echo $this->_context->echostr;die;
	        }else{
	            Helper_Common::log('weixin: acctname='.$acctname.' make='.$make.' sign='.$this->_context->signature);
	            die;
	        }
	    }else if ( $this->_context->isPOST())
	    {
	        $request = file_get_contents('php://input', 'r');
	        Helper_Common::log(print_r($request,true));
            $response = helper_weixin::response($acct->id,$request);
            echo $response;
            die;
	    }
	}
	
	function json($code,$msg)
	{
		$array = array('errcode'=>intval($code),'errmsg'=>trim($msg));
		exit(json_encode($array));
	}
	/**
	 * 手机快速注册
	 */
	function actionquickreg()
	{
		//	URL:/interface/quickreg/acctname/手机号码/pwd/自定义密码/key/a88aa9eacb67a03eb63fa7e867ea57b8
		$acctname = trim($this->_context->acctname);
		$acctname = Helper_Common::trim($acctname);
		$pwd = trim($this->_context->pwd);
		$key = 'a88aa9eacb67a03eb63fa7e867ea57b8';
		$acctuser = Acctuser::checkAcctname($acctname);
		if (!Helper_Param::_call($acctname))
		{
			$this->json(4, '手机号码格式不正确');
		}
		if ($acctuser->id())
		{
			$this->json(1, '号码已经被注册');
		}else{
			$acct = Acct::find('wapquickkey = ?',$key)->getOne();
			if (!$acct->id())
			{
				$this->json(2, '代理不存在');
			}else{
				if ($acct->wapquickopen == 0)
				{
					$this->json(3, '代理未打开手机快速注册');
				}else{
					
					$count = Wapquickreg::find('acctname = ? and created >= ?',$acctname,time()-60)->getCount('id');
					if($count)$this->json(4, '60秒内只能获取1次');
					$code = Helper_Common::get_rnd(0, 6);
					$Log = new Wapquickreg();
					$Log->acctkey = $key;
					$Log->code = $code;
					$Log->acctname = $acctname;
					$Log->pwd = $pwd;
					$Log->status =0;
					$Log->save(0,'create');
					$smsurl = $acct->smsurl ;
					$smsurl = str_replace('%m%', $acctname, $smsurl);
					$smsurl = str_replace('%s%', "您的快捷注册验证码为:{$code}", $smsurl);
					$smsresult = Helper_Common::cget($smsurl);
					Helper_Common::log("interface/quickreg url:{$smsurl},result:{$smsresult}",'quickreg');
					$this->json(0, '验证码已经发送,请注意查收');
				}
			}
		}
	}
	/**
	 * 使用验证码注册
	 */
	function actionquickcheckcode()
	{
		$acctname = trim($this->_context->acctname);
		$acctname = Helper_Common::trim($acctname);
		$code =intval($this->_context->code);
		$acctuser = Acctuser::checkAcctname($acctname);
		if($acctuser->id())
		{
			$this->json(1, '用户已经注册');
		}else{
			if(!$code)
			{
				$this->json(2, '验证码格式错误');
			}else{
				$log = Wapquickreg::find('acctname = ? and status = 0',$acctname)->order('created desc')->getOne();
				if(!$log->id())
				{
					$this->json(3, '请先获取验证码');
				}else{
					if(intval($log->code) === $code)
					{
						$acct = Acct::find('wapquickkey = ? and wapquickopen = 1',$log->acctkey)->getOne();
						if (!$acct->id())
						{
							$this->json(4, '代理已经不存在');
						}
						$acctwap = Acctwapset::find('acctid = ? ',$acct->id)->getOne();
						$acctuser = new Acctuser();
						$acctuser->agent_id = $acct->id;
						$acctuser->admin_id = $acct->admin_id;
						$acctuser->unionacctname = '';
						$acctuser->acctname = $acctname;
						$acctuser->password = $log->pwd;
						$acctuser->balance = $acctwap->safe_money;
						$acctuser->activedate = date('Y-m-d');
						$acctuser->expireddays = $acctwap->expireddays;
						$acctuser->expireddate = date('Y-m-d',strtotime("{$acctuser->activedate} + {$acctuser->expireddays} day"));
						//$acctuser->bindexten_type = 0;
						//$acctuser->expireddays = $card->expireddays;
						$acctuser->changeagent = 1;
						$acctuser->rategroupid = $acctwap->rategroupid;
						$acctuser->rategroupid_acall = $acctwap->rategroupid_acall;
						$acctuser->limitbalance = 0;
						$acctuser->bind_ipphone = $acctname;
						try {
							$acctuser->save(0,'create');
							Syslog::notloginlogs("{$acct->acctname} 下的 {$acctname} 使用手机验证码{$code} 成功注册");
							$log->status = 1;
							$log->save(0);
														//return true;
						} catch (Exception $e) {
								
						}
						$result = '注册成功';
						$sql = "call fscall.httppost('{$acctname}','','',1)";
						QDB::getConn()->execute($sql);
						QDB::getConn()->close();
						$this->json(0, '注册成功');
					}else{
						$this->json(4,'验证码错误');
					}
				}
			}
		}
	}
	function actiontransfer()
	{
		///interface/transfer/acctname/转账帐号/password/转账密码/tar_acctname/转入帐号/tar_balance/转入金额
		$acctname = Helper_Common::trim($this->_context->acctname);
		$pwd = trim($this->_context->password);
		$tar_acctname = Helper_Common::trim($this->_context->tar_acctname);
		$tar_balance = ($this->_context->tar_balance);
		if(!$acctname || !$pwd || !$tar_acctname)$this->json(2, '参数不完整');
		$status = Acctuser::transfer($acctname, $pwd, $tar_acctname, $tar_balance);
		if ($status === true)
		{
			Syslog::notloginlogs("{$acctname} 转账 {$tar_balance} 给 {$tar_acctname} ");
			$this->json(0, "转账成功");
		}else
		{
			$this->json(1, $status);
		}
	}
	
}